<?php

namespace app\agent\model;

use think\facade\Db;
use think\facade\Request;

class Config
{
    private $table = 'agent_config';

    /**
     * 获取配置
     */
    public function get($agentId)
    {
        $info = Db::name($this->table)
            ->where('agent_id', $agentId)
            ->findOrEmpty();
        if (isProd()) {
            $info['ip'] = '47.98.233.82';
        } else {
            $info['ip'] = '120.78.169.136';
        }
        $info['url'] = Request::domain() . '/api/wechat/push';
        return success('操作成功', $info);
    }

    /**
     * 更新
     */
    public function set($params)
    {
        $id = Db::name($this->table)
            ->where('agent_id', $params['agent_id'])
            ->value('id');

        Db::startTrans();
        try {
            if ($id) {
                Db::name($this->table)
                    ->where('id', $id)
                    ->strict(false)
                    ->update($params);
            } else {
                if (empty($params['ali_public_key'])) {
                    $params['ali_public_key'] = '';
                }
                if (empty($params['ali_private_key'])) {
                    $params['ali_private_key'] = '';
                }
                $id = Db::name($this->table)
                    ->strict(false)
                    ->insertGetId($params);
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();

            return fail('操作失败：' . $e->getMessage());
        }

        return success('操作成功', [
            'id' => intval($id),
        ]);
    }

    /**
     * 上传证书
     */
    public function uploadCert()
    {
        try {
            $file = request()->file('file');
            // 上传到本地服务器
            $savePath = date('Ymd') . '/' . md5((string) microtime(true)) . '/' . $file->getOriginalName();
            $savename = \think\facade\Filesystem::disk('cert')->putFileAs('cert', $file, $savePath);
            $savename = str_replace('\\', '/', $savename);
        } catch (\Exception $e) {
            return fail('上传失败：' . $e->getMessage());
        }

        return success('上传成功', [
            'url' => $savename,
        ]);
    }
}
